﻿using Share;
using Microsoft.SemanticKernel;
using PluginSQLDemo.Plugins;
using Microsoft.SemanticKernel.ChatCompletion;
using PluginSQLDemo;
using System.Text.Json;
using Microsoft.SemanticKernel.Connectors.OpenAI;

const string createPrompt =
    @"
# 背景
您是一个Sql助手，我会提供很多用于执行Sql的Function，您需要根据需求选择合适的Function来执行Sql语句，返回结果给用户。

## 需求
操作：{{$action}}
Sql语句：{{$sql}}
是否存在返回结果：{{$IsResult}}
";

var kernel = Kernel.CreateBuilder()
     .AddOpenAIChatCompletion(
    modelId: "4.0Ultra",
    apiKey: "sk-9gH1lRVZemdh4eStDMJllCSLLt9VTq4ls18orr",
    httpClient: new HttpClient(new OpenAIHttpClientHandler("https://api.token-ai.cn/")))
    .Build();

kernel.Plugins.AddFromType<FreeSqlPlugin>();

var pluginsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Plugins", "BasePlugins");

var basePlugins = kernel.ImportPluginFromPromptDirectory(pluginsDirectory);

var chat = kernel.GetRequiredService<IChatCompletionService>();

while (true)
{
    Console.Write("User=>");
    var input = Console.ReadLine();
    if (input == "exit")
    {
        break;
    }

    var result = await kernel.InvokeAsync(basePlugins["SqliteSystem"], new KernelArguments()
    {
        ["input"] = input
    });

    var values = JsonSerializer.Deserialize<SqlAction[]>(result.ToString());

    foreach (var value in values)
    {
        Console.WriteLine($"Action: {value.Action} Sql: {value.Sql} IsResult: {value.IsResult}");

        var chatMessageContents = await chat.GetChatMessageContentsAsync(createPrompt
            .Replace("{{$action}}", value.Action)
            .Replace("{{$sql}}", value.Sql)
            .Replace("{{$isResult}}", value.IsResult.ToString()), new OpenAIPromptExecutionSettings()
            {
                ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
            }, kernel);

        foreach (var chatMessageContent in chatMessageContents)
        {
            Console.WriteLine(chatMessageContent.Content);
        }
    }
}